<?php declare(strict_types=1);

namespace app\admin\controller;

use app\admin\Diluma;
use app\admin\service\AuditService;
use app\admin\service\userService;
use app\admin\model\User as UserModel;
use think\facade\View;

class User extends Diluma
{

    /**
     * 用户
     * @return string
     */
    public function index()
    {
        return View::fetch();
    }

    /**
     * 用户列表
     * @return void
     */
    public function getUserList()
    {
        $startDate = $this->request->param('start_date');
        $endDate = $this->request->param('end_date');
        $keywords = $this->request->param('keywords');
        $vip = $this->request->param('is_vip');
        $gender = $this->request->param('gender');
        $pageSize = (int)$this->request->param('page_size', 10);
        $service = new UserService();
        $list = $service->getUserList($pageSize, $startDate, $endDate, $keywords, $vip, $gender);
        return json(['code'=>0, 'count'=>$list->total(), 'data'=>$list->items()]);
    }

    /**
     * 编辑用户
     * @return \think\response\Json
     */
    public function edit()
    {
        $service = new UserService();
        if($this->request->isPost()) {
            $post = $this->request->post();
            $model = new UserModel();
            $item = $model->find($post['field']['id']);
            if (empty($item)) {
                return json(['code'=>1, 'msg'=>"用户不存在，修改失败"]);
            }
            if(false === $item->save($post['field'])) {
                return json(['code'=>1, 'msg'=>"修改失败，请稍后再试"]);
            } else {
                return json(['code'=>0, 'msg'=>"修改成功"]);
            }
        } else {
            $userId= $this->request->param('id');
            $item = $service->getUserProfile($userId);
            View::assign('item', $item);
            return View::fetch();
        }
    }

    /**
     * 会员
     * @return string
     */
    public function vip()
    {
        return View::fetch();
    }

    /**
     * 会员列表
     * @return void
     */
    public function getVipList()
    {
        $userId = $this->request->param('user_id');
        $keywords = $this->request->param('keywords');
        $pageSize = $this->request->param('page_size', 10);
        $user = new UserService();
        $items = $user->getVipList($pageSize, $userId, $keywords);
        return json(['code'=>0, 'count'=>$items->total(), 'data'=>$items->items()]);
    }

    /**
     * 银行卡
     * @return \think\response\Json
     */
    public function bank(): \think\response\Json
    {
        $post = $this->request->post();
        $res = (new AuditService())->bank($post);
        if ($res) {
            return json(['code'=>0, 'msg'=>'更新成功']);
        } else {
            return json(['code'=>1, 'msg'=>'更新失败，请稍后再试']);
        }
    }
}